<!-- pages/login/components/mobile.vue -->
<script setup>
	import {
		ref
	} from "vue"

	import {
		useUserStore
	} from "@/store/module/user.js"
	import {
		verfyCodeApi,
		loginByMobileApi
	} from "@/api/user.js"
	const showCountdom = ref(false)

	const fromData = ref({
		mobile: '',
		code: ''
	})

	const userStore = useUserStore()
	const fromRef = ref()

	const isgree = ref(false)
	// 验证表单数据的规则
	const formRules = {
		mobile: {
			rules: [{
					required: true,
					errorMessage: '请填写手机号码'
				},
				{
					pattern: '^1\\d{10}$',
					errorMessage: '手机号码格式不正确'
				},
			],
		},
		code: {
			rules: [{
					required: true,
					errorMessage: '请输入验证码'
				},
				{
					pattern: '^\\d{6}$',
					errorMessage: '验证码格式不正确'
				},
			],
		},
	}
	const onTextButtonClick = async () => {
		showCountdom.value = true

		const {
			data
		} = await verfyCodeApi({
			mobile: fromData.value.mobile,
			type: 'login'
		})
		// console.log(res, 111);
		fromData.value.code = data.code


	}
	const oncounttimeup = () => {
		showCountdom.value = false
	}
	const onFromSubment = async () => {
		if (!isgree.value) return uni.utils.toast('请勾选协议！')
		try {
			const result = await fromRef.value.validate()
			const res = await loginByMobileApi(result)
			userStore.token = res.data.token
			// uni.switchTab({
			// 	url: '/pages/index/index'
			// })
			// uni[userStore.openType]({
			// 	url: userStore.redirectURL
			// })

			if (userStore.openType === 'switchTab') {
				uni.switchTab({
					url: userStore.redirectURL
				})
			} else {
				uni.redirectTo({
					url: userStore.redirectURL
				})
			}
		} catch {}

	}
	const onAgreeckicl = () => {
		isgree.value = !isgree.value
	}
</script>

<template>
	<uni-forms class="login-form" :rules="formRules" ref="fromRef" :model="fromData">
		<uni-forms-item name="mobile">
			<uni-easyinput v-model="fromData.mobile" :input-border="false" :clearable="false" placeholder="请输入手机号"
				placeholder-style="color: #C3C3C5" />
		</uni-forms-item>
		<uni-forms-item name="code">
			<uni-easyinput v-model="fromData.code" :input-border="false" :clearable="false" placeholder="请输入验证码"
				placeholder-style="color: #C3C3C5" />
			<view v-if="showCountdom" class="test-button">
				<uni-countdown @timeup="oncounttimeup" :show-day="false" :show-hour="false" :show-minute="false"
					second="10"></uni-countdown>秒后重新获取
			</view>
			<text v-else @click="onTextButtonClick" class="text-button">获取验证码</text>
		</uni-forms-item>

		<view class="agreement">
			<radio @click="onAgreeckicl" :checked="isgree" color="#16C2A3" />
			我已同意
			<text class="link">用户协议</text>
			及
			<text class="link">隐私协议</text>
		</view>

		<button class="uni-button" @click="onFromSubment">登 录</button>
	</uni-forms>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<style lang="scss">
	@import './styles.scss';
</style>